package darknet

import (
	"time"

	"gitee.com/dark.H/dark"
	"gitee.com/dark.H/darknet/tcp"
)

func PingAlive(ipOrRage dark.Str) (alives dark.List[dark.Str]) {

	args := dark.List[string].Add(RangeIP(ipOrRage.Split(".")[:3].Join(".") + ".0/24").List()).AsAny()
	NewPool(50).Map(args, func(no int64, i any) any {
		pinger, _ := NewPinger(i.(string))
		pinger.Count = 3
		pinger.Timeout = time.Second * 2
		err := pinger.Run()
		if err != nil {
			return nil
		}
		stats := pinger.Statistics()
		if stats.PacketsRecv > 0 {
			return i.(string)
		}
		return nil
	}, func(i any) {
		if i != nil {
			alives = append(alives, dark.Str(i.(string)))
		}
	})
	return
}

func TcpPortAlive(args dark.List[string], proxy ...string) (alives dark.List[dark.Str]) {
	pool := NewPool(50)
	// alives := dark.List[string]{}
	go pool.AsyncOutput(func(result any) {
		if result != nil {
			alives = append(alives, result.(dark.Str))
		}
	})

	args.Every(func(ix int, i string) {
		pool.Async(func(no int64) any {
			if tcp.TestAlive("tcp", dark.Str(i), proxy...) {
				return dark.Str(i)
			}
			return nil
		})
	})
	pool.WaitStop()
	return
}
